package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.updateStock";

    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        // 查询
        List<Sku> list = query().eq("spu_id", spuId).list();
        // 转换DTO
        return SkuDTO.convertEntityList(list);
    }

    @Transactional
    @Override
    public void deductStock(Map<Long, Integer> skuMap) {
        try {
            executeBatch(sqlSession -> {
                // 编译sql，设置参数
                for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
                    // 准备参数
                    Map<String,Object> param = new HashMap<>();
                    param.put("id", entry.getKey());
                    param.put("num", entry.getValue());
                    // 指定statement的id和对应参数。statementId其实就是mapper的 namespace + methodName
                    sqlSession.update(UPDATE_STOCK_STATEMENT, param);
                }
                // 刷新并执行Sql
                sqlSession.flushStatements();
            });
        } catch (Exception e) {
            throw new LyException(400, "更新库存失败，可能是库存不足");
        }
    }
}
